package uit.edu.vn.Activity;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;

import uit.edu.vn.Model.myFile;
import uit.edu.vn.Model.myMusic;
import uit.edu.vn.Model.mySMS;
import uit.edu.vn.Utility.FileListAdapter;
import uit.edu.vn.Utility.MyActivity;
import uit.edu.vn.Utility.xStreamXML;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SmsRestoreSDCardActivity extends MyActivity  {

	private ListView listview;
	private TextView titleHeader;
	private Context context;
	private Resources res;
	private int numberOfItemSelected = 0;	
	private ProgressDialog loadingSmsDialog;
	private String path=Environment.getExternalStorageDirectory()+"/BackupManager/SMS";
	private ArrayList<myFile> listFiles = new ArrayList<myFile>();
	
	private ArrayList<mySMS> listFileRestore= new ArrayList<mySMS>();
	private FileListAdapter fAdapter ;
    private static final String STRING_NAME_USERSETTING = "USER REFERENCES";
    private SharedPreferences ShareRef = null;
	
//    private int userid = LoginActivity.getUserID();
    private String username = "";
    private String password = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.backup_file);
        username = getSetting("username");
        password = getSetting("password");
	      //kiem tra neu username va password rong thi ket thuc activity hien tai va goi activity login
	      if(username.equals("") && password.equals("")){
	          Intent intent = new Intent(SmsRestoreSDCardActivity.this, LoginActivity.class);
	          startActivity(intent);
	          this.finish();            	
	      }
			File dir = new File(path);
			dir.mkdirs();
			System.out.println("path save sms:" + path);
		listview =(ListView)findViewById(R.id.listFileBackup);
		titleHeader=(TextView)findViewById(R.id.txt_titleFile);
		titleHeader.setText(R.string.title_RestoreHeaderSmsSDcard);
		context=getBaseContext();
		res=getResources();
		loadingSmsDialog= new ProgressDialog(this);
		loadingSmsDialog.setMessage(getResources().getString(R.string.dialog_message_progress_sdcard));
		loadingSmsDialog.setCancelable(false);
		loadingSmsDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		//ham load tat ca file tu 1 duong dan
		new BackGroundTask().execute();
		listview.setOnItemClickListener(new OnItemClickListener() 
        {
     	   @Override
     	   public void onItemClick(AdapterView<?> arg0, View arg1, final int position,	long arg3) {   		   
     		   	try {		   		
							// TODO Auto-generated method stub
							myFile entry = listFiles.get(position);
							
							File temp = new File(entry.getPath());
							final Dialog dialog=new Dialog(SmsRestoreSDCardActivity.this);
			 	    		dialog.setContentView(uit.edu.vn.Activity.R.layout.file_dialog);
			 	    		dialog.setTitle("Thông tin tập tin ");
			 	    		TextView txt_filename= (TextView)dialog.findViewById(R.id.txt_nameDialog);
			 	    		TextView txt_filesize= (TextView)dialog.findViewById(R.id.txt_sizeDialog);
			 	    		txt_filename.setText(temp.getName());
			 	    		txt_filesize.setText(entry.getSize());	    		
			 	    		
			 	    		Button btn_ok = (Button)dialog.findViewById(R.id.btn_okDialog);
			 	    		btn_ok.setOnClickListener(new View.OnClickListener() {								
								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
			 	    		dialog.show();
						}				
     		   	 catch (Exception e) {
					// TODO: handle exception
					  e.printStackTrace();
				}
     		   	
     		   	
     	   }
       
	});
	}
	
	public String getSetting(String key) {
        ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
        return ShareRef.getString(key, "");
	}
	
	private class BackGroundTask extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			loadingSmsDialog.show();
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
                Thread.sleep(1000);

    			getdir(path);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			loadingSmsDialog.cancel();
			fAdapter= new FileListAdapter(context, listFiles);
		
			listview.setAdapter(fAdapter);
			super.onPostExecute(result);
		}
		
	}
	private void getdir(String path)
	{
		try
		{
			String size;
			//lay duong dan cua folder chua file restore
			File f= new File(path);
			File[] files= f.listFiles();
			for(int i=0; i<files.length;i++)
			{
				File file = files[i];
			
            	if(file.length()<1024)
            	{
            		size=file.length()+" Byte";   
            	}
            	else
            	{
            		long temp=file.length()/1024;
            		 size =String.valueOf(temp)+" KB"; 
            	}
				listFiles.add(new myFile(file.getName(),file.getPath(), size, res.getDrawable(R.drawable.ic_text)));
			}
		}
		catch(Exception e)
		{
			
			e.printStackTrace();
		}
	}

//--------------------------------xu ly menu ------------------------------------------------------------
	// tao menu option 
	public boolean onCreateOptionsMenu(Menu menu) 
	{
	    	// TODO Auto-generated method stub	    	
		new MenuInflater(getApplicationContext()).inflate(R.menu.restore_option_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    	// TODO Auto-generated method stub
	    switch(item.getItemId())
	    {
	    	case R.id.menu_restore_File: 		
	    		// duyet mang file va lay nhung file nao duoc check 
	    		int flag=0;
				for(int i=0;i<listFiles.size();i++)
				{
					if(listFiles.get(i).getChecked()==true)
					{
						flag=1;
						numberOfItemSelected++;
					}
				
				}
				if(flag==0)
				{
					numberOfItemSelected=0;
				}
    			if(numberOfItemSelected==0)
    			{
    				showToast("Vui lòng chọn tin nhắn cần phục hồi");
    			}
    			else
    			{	showConfirmDialog(getResources().getString(R.string.dialog_thongbao),getResources().getString(R.string.dialog_message_phuchoisms), new OnClickListener() 
	    			{
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							new AsyncTask<Void, Void, Void>()
							{
								@Override
								protected void onPreExecute() {
									// TODO Auto-generated method stub
									super.onPreExecute();
									loadingSmsDialog.setMessage("Đang phục hồi tin nhắn từ thẻ nhớ ");
									loadingSmsDialog.show();
								}	
								@Override
								protected Void doInBackground(Void... params) 
								{
									// TODO Auto-generated method stub
									try 
									{
										
			                            Thread.sleep(1000);                   
			                            for(int i=0;i<listFiles.size();i++)
			        	    			{
			                            	
			                            	if(listFiles.get(i).getChecked()==true)
			                            	{
			                            		restoreSMSFromSdcard(listFiles.get(i).getPath());
			                            	
			                            	}
			                            	
			        	    			}
				    			
			                        } 
									catch (Exception e)
			                        {
			                            // TODO Auto-generated catch block
			                            e.printStackTrace();
			                        }
									return null;
								}
								@Override
								protected void onPostExecute(Void result) 
								{
									// TODO Auto-generated method stub
									loadingSmsDialog.dismiss();

//			    					duyet mang và set check lai false
		                            for(int i=0;i<listFiles.size();i++)
									{
										listFiles.get(i).setChecked(false);
									}
									fAdapter.notifyDataSetChanged();
									showAlertDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_phuchoithanhcong), new OnClickListener() {
										
										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											dialog.dismiss();
										}
									});
									super.onPostExecute(result);
								}
							}.execute();
						}
	    			
					});
    			}
	    			return true;
	    
	    	case R.id.menu_restore_Delete:
	    			// duyet mang file de xem file nào đc check
	    			// xong xóa file theo tên file
	    		int flag1=0;
				for(int i=0;i<listFiles.size();i++)
				{
					if(listFiles.get(i).getChecked()==true)
					{
						flag1=1;
						numberOfItemSelected++;
					}
				
				}
				if(flag1==0)
				{
					numberOfItemSelected=0;
				}
    			if(numberOfItemSelected==0)
    			{
    				showToast("Vui lòng chọn tin nhắn cần xóa");
    			}
    			else
    			{	showConfirmDialog(getResources().getString(R.string.dialog_canhbao), getResources().getString(R.string.dialog_message_xoa), new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
			
						
						// TODO Auto-generated method stub
						Log.d("tag",String.valueOf(listFiles.size()));
						try{

							for(int i=0;i<listFiles.size();i++)
							{
								if(listFiles.get(i).getChecked()==true)
								{
									Log.d("i",String.valueOf(i));
									File temp= new File(listFiles.get(i).getPath());
									Log.d("tag", listFiles.get(i).getPath());
									
									Boolean delete=temp.delete();
									listFiles.remove(i);	
									fAdapter.notifyDataSetChanged();
									if(delete ==true)
									{
										i--;
									}			    					
								}			
							}
				
						}
						catch (Exception e) 
						{
							// TODO: handle exception
							e.printStackTrace();
						}
						//thong báo xóa file thành công
						showAlertDialog(getResources().getString(R.string.dialog_thongbao),getResources().getString(R.string.dialog_message_xoathanhcong), new OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								//duyet mang và set check lai false
								for(int i=0;i<listFiles.size();i++)
								{
									listFiles.get(i).setChecked(false);
								}
								
								dialog.cancel();
								}
						});
						
					}
	    			}).show();
	    	
	    	    	}
	    			return true;
	    	case R.id.menu_restore_Logout:
	    		logOut();
    			Intent intent = new Intent(SmsRestoreSDCardActivity.this, LoginActivity.class);
    			startActivity(intent);
    			this.finish();
    			return true;		
	    			
	    }
	    return false;
	}   
//	-------------- cac ham xu ly -----------------------
	public void restoreSMSFromSdcard(String pathFile)
	{
		File file = new File(pathFile);
		FileReader fr;
		try {
			fr = new FileReader(file);
			listFileRestore=xStreamXML.smsfromXML(fr);
			if(!listFileRestore.isEmpty())
			{
				Log.d("tag", "list co du lieu");
			}	
			else 
				Log.d("tag", "list rong");
			ContentValues value= new ContentValues();
			for(int i=0;i<listFileRestore.size();i++)
			{
				//value.put("_id", listFileRestore.get(i).getID());
				value.put("thread_id", listFileRestore.get(i).getThreadID());
				value.put("address", listFileRestore.get(i).getSMSName());
				value.put("body", listFileRestore.get(i).getSMSBody());
				value.put("date", listFileRestore.get(i).getCurrent());
				value.put("type", listFileRestore.get(i).getType());
				value.put("protocol", listFileRestore.get(i).getProtocol());	
				context.getContentResolver().insert(Uri.parse("content://sms/inbox"), value);
				
			}
			
			
			//showToast("Restores xong");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			showToast("Lỗi trong lúc phục hồi");
			e.printStackTrace();
		}
		
		
	}
}
